package org.abettor.pushbox.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.abettor.pushbox.R;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadNotify;
import org.abettor.pushbox.download.ParaNotify;
import org.abettor.pushbox.model.NotifyBean;
import org.abettor.pushbox.model.NotifyConfigBean;
import org.abettor.pushbox.model.SelfMessage;
import org.abettor.pushbox.notify.NotifyUtil;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * 更新通知的操作
 * @author jzh
 * 
 */
public class UpdateNotifyService extends Service {
	private Handler mHandler = new Handler();
	private final IBinder mBinder = new LocalBinder();
	private Timer timer = null;
	private TimerTask timerTask;// 定期执行的任务
	private DownloadNotify download = new DownloadNotify();

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		startTimerTask();// 开始任务调用
		Log.i("begin", "begin scheding...");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	// 开始任务调用
	private void startTimerTask() {
		timer = new Timer();
		timerTask = new MyTask();
		NotifyConfigBean bean = Config.readNotifyConfigBean(this);
		if (!bean.getIsOpenNotify().equals(NotifyConfigBean.OPENNOTIFY)) {// 读取是否
			this.stopSelf();
			return;
		}

		timer.schedule(timerTask, bean.getSleepTime(), bean.getSleepTime());
	}

	// 停止任务调用
	private void stopTimerTask() {
		timer.cancel();
	}

	// 重启任务调用
	private void restartTimerTask() { 
		stopTimerTask();
		startTimerTask();
	}

	public class LocalBinder extends Binder {
		public UpdateNotifyService getService() {
			return UpdateNotifyService.this;
		}
	}

	public class MyTask extends TimerTask {
		@Override
		public void run() {
			readNotifyFromNet();
		}
	}

	// 读取网络消息
	private void readNotifyFromNet() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nickName = null;
		String dateTime = null;
		SelfMessage self = Config.readSelfMessage(this);
		if (self != null) {
			nickName = self.getNickName();
		}
		NotifyConfigBean config = Config.readNotifyConfigBean(this);
		if(!config.getIsOpenNotify().equals(NotifyConfigBean.OPENNOTIFY)){//没有处于开启状态关闭
			stopTimerTask();
			//把自己停止掉
			this.stopSelf();
			return;
		}
		dateTime = config.getLastAccessTime();
		String content = download.readNotify(nickName, dateTime);
		if (content == null) {
			return;
		}
		// 解析时间
		Date date = ParaNotify.paraLastDate(content);
		Log.i("time", date.toLocaleString());
		if (date == null) {
			return;
		}
		List<NotifyBean> list = ParaNotify.paraNotifyBean(content);
		if (list == null || list.isEmpty()) {
			config.setLastAccessTime(sdf.format(date));
			Config.writeNotifyConfigBean(this, config);
			return;
		}
		boolean flag = false;
		for (NotifyBean bean : list) {
			if (bean.getType() == NotifyBean.CHANGE_UPDATETIME) {
				config.setSleepTime(Long.parseLong(bean.getId()));
				flag = true;
			} else {
				notifyUser(bean);
			}
		}
		config.setLastAccessTime(sdf.format(date));
		Config.writeNotifyConfigBean(this, config);
		if (flag) {
			restartTimerTask();
		}
	}

	// 通知用户的操作
	private void notifyUser(final NotifyBean bean) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				Notification notification = new Notification(
						R.drawable.icon, NotifyUtil.readNotifyTitle(UpdateNotifyService.this, bean), System.currentTimeMillis());
				notification.defaults |= Notification.DEFAULT_SOUND;
				notification.defaults |= Notification.DEFAULT_LIGHTS;
				Intent notificationIntent = NotifyUtil.readNotifyIntent(UpdateNotifyService.this, bean);
				if(notificationIntent == null)
				{
					return;
				}

				PendingIntent contentIntent = PendingIntent.getActivity(
						UpdateNotifyService.this, 0, notificationIntent, 0);
				notification.setLatestEventInfo(UpdateNotifyService.this,
						NotifyUtil.readNotifyTitle(UpdateNotifyService.this, bean), NotifyUtil.readNotifyMsg(UpdateNotifyService.this, bean), contentIntent);
				mNotificationManager.notify(NotifyBean.NOTIFY_TAG, bean.getType(), notification);
			}
		});
	}
}
